package com.wdh.kjs.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.activity.AccountDetailsActivity;
import com.wdh.kjs.activity.AccountOverviewActivity;
import com.wdh.kjs.activity.FinanceManageActivity;
import com.wdh.kjs.activity.FinanceManageActivity2;
import com.wdh.kjs.activity.InvestManageActivity;
import com.wdh.kjs.activity.InvestManageActivity2;
import com.wdh.kjs.activity.LoginActivity;
import com.wdh.kjs.activity.MoneyFlowingActivity2;
import com.wdh.kjs.activity.MyAccountTopTurnActivity;
import com.wdh.kjs.activity.RechargeActivity;
import com.wdh.kjs.activity.SecuritySetting;
import com.wdh.kjs.activity.WithdrawActivity;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.ToastUtils;

import java.math.BigDecimal;

/**
 * Created by codingWw on 2016/3/7.
 */
public class MyAccountFragment extends Fragment implements View.OnClickListener{

    private ImageView iv_myAccountTopTurn;
    private ImageView accountDetail;
    private LinearLayout accountOverview;
    private LinearLayout investmentManagement;
    private LinearLayout moneyFlowing;
    private LinearLayout financeManagement;
    private LinearLayout securitySetting;
    private Button recharge;
    private Button withdraw;
    private Intent intent;
    private TextView totalAssert;
    private TextView availableBalance;
    private TextView blockedBalance;
    private JsonModel_my jsonModel_my;
    private String partyId;
    private LinearLayout userIcon;
    private String phoneNumber;
    private String nickName;
    private TextView myaccount_text;
    private TextView myaccount_hello;
    private TextView iv_myAccountTopRed;
    private String unReadTotal="";

    private JsonModel jsonModel;
    private String zhanghao;
    private String mima;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_myaccount, container, false);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("logininfo", Context.MODE_PRIVATE);
        partyId = sharedPreferences.getString("loginToken", "");
        nickName = sharedPreferences.getString("nickName", "");
        zhanghao = sharedPreferences.getString("zhanghao", "");
        mima = sharedPreferences.getString("mima", "");
        initview(view);
        phoneNumber = sharedPreferences.getString("phoneNumber", "请登录");

        intweb();

        initwidge();
        if (!partyId.equals("")) {
            loadData();
            if (!nickName.equals("")) {
                myaccount_text.setText(nickName+"，您好");
                myaccount_hello.setVisibility(View.VISIBLE);
                initdenglu();

            }
            else
                myaccount_text.setText(phoneNumber);
                myaccount_hello.setVisibility(View.VISIBLE);
        }else {
            myaccount_text.setText("未登录");
        }
        return view;
    }

    private void initdenglu() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("USERNAME", zhanghao);
        params.addBodyParameter("PASSWORD", mima);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_LOGIN, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                String m = jsonModel.getPartyId();
                if (jsonModel._LOGIN_PASSED_()) {
                    SharedPreferences.Editor editor = getActivity().getSharedPreferences("logininfo", getActivity().MODE_PRIVATE).edit();
                    editor.putString("nickName", jsonModel.getNickName());
                    editor.commit();
                    myaccount_text.setText(jsonModel.getNickName()+"，您好");
                    myaccount_hello.setVisibility(View.VISIBLE);

                }
            }


            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });

    }

    @Override
    public void onResume(){
        super.onResume();
        Log.i("ddd", "dddddddddd");
        intweb();
    }

    private void loadData() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_MY_ACCOUNT, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
//                Log.i("msg","666");
                if (jsonModel_my.success) {
                    availableBalance.setText("￥" + new BigDecimal(jsonModel_my.getUserVirtualAccount().getTotalAssets().toString()).setScale(2));
                    totalAssert.setText("￥" + new BigDecimal(jsonModel_my.getUserVirtualAccount().getAvailableBalance().toString()).setScale(2));
                    blockedBalance.setText("￥" + new BigDecimal(jsonModel_my.getUserVirtualAccount().getBlockedBalance().toString()).setScale(2));
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });

    }
    private void initwidge() {
        iv_myAccountTopTurn.setOnClickListener(this);
        securitySetting.setOnClickListener(this);
        accountDetail.setOnClickListener(this);
        accountOverview.setOnClickListener(this);
        investmentManagement.setOnClickListener(this);
        financeManagement.setOnClickListener(this);
        moneyFlowing.setOnClickListener(this);
        recharge.setOnClickListener(this);
        withdraw.setOnClickListener(this);
        userIcon.setOnClickListener(this);
    }

    private void initview(View view) {
        myaccount_hello = (TextView) view.findViewById(R.id.myaccount_hello);
        myaccount_text = (TextView) view.findViewById(R.id.myaccount_text);
        userIcon = (LinearLayout) view.findViewById(R.id.userIcon);
        iv_myAccountTopTurn = (ImageView) view.findViewById(R.id.iv_myAccountTopTurn);
        accountDetail = (ImageView) view.findViewById(R.id.accountDetail);
        accountOverview = (LinearLayout) view.findViewById(R.id.accountOverview);
        investmentManagement = (LinearLayout) view.findViewById(R.id.investmentManagement);
        financeManagement = (LinearLayout) view.findViewById(R.id.financeManagement);
        moneyFlowing = (LinearLayout) view.findViewById(R.id.moneyFlowing);
        securitySetting = (LinearLayout) view.findViewById(R.id.securitySetting);
        recharge = (Button) view.findViewById(R.id.recharge);
        withdraw = (Button) view.findViewById(R.id.withdraw);
        totalAssert = (TextView) view.findViewById(R.id.totalAssert);
        availableBalance = (TextView) view.findViewById(R.id.availableBalance);
        blockedBalance = (TextView) view.findViewById(R.id.blockedBalance);
        iv_myAccountTopRed = (TextView) view.findViewById(R.id.iv_myAccountTopRed);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==110){
            if(resultCode==111){
                if(data.getStringExtra("unReadTotal").equals("0")){
                    Log.i("msg","ninininininininini");
                    intweb();
                }
            }
        }

    }

    private void intweb() {
        if (!partyId.equals("")) {
            RequestParams params = new RequestParams();
            params.addBodyParameter("partyId", partyId);
            params.addBodyParameter("page", "1");
            params.addBodyParameter("rows", "5");
            HttpUtils http = new HttpUtils();
            http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_STSTION_MESSAGE, params, new RequestCallBack<String>() {

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {

                    Gson gson = new Gson();
                    jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
//                    if (jsonModel_my.success) {
//                        unReadTotal = jsonModel_my.getUnReadTotal() + "";
//
//                        if (jsonModel_my.getUnReadTotal() > 0) {
//                            iv_myAccountTopRed.setVisibility(View.VISIBLE);
//                            iv_myAccountTopRed.setText(unReadTotal);
//                        } else {
//                            iv_myAccountTopRed.setVisibility(View.GONE);
//                        }
//                    }
                }

                @Override
                public void onFailure(HttpException error, String msg) {

                    ToastUtils.showShort(getContext(), "网络异常！");
                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.userIcon:
                if (partyId.equals("")) {
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);
                }
                break;
            case R.id.iv_myAccountTopTurn:
                if (partyId.equals("")) {
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);
                }
                else{
                    intent = new Intent();
                    intent.setClass(getActivity(), MyAccountTopTurnActivity.class);
                    startActivityForResult(intent, 110);
                    }
                break;
            case R.id.accountDetail:
                if (partyId.equals("")) {
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);
                }
                else{
                    intent = new Intent(getActivity(), AccountDetailsActivity.class);
                startActivity(intent);}
                break;
            case R.id.accountOverview:
                if (partyId.equals("")){
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);}
                else{
                    intent = new Intent(getActivity(), AccountOverviewActivity.class);
                startActivity(intent);}
                break;
            case R.id.investmentManagement:
                if (partyId.equals(""))
                {
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);}
                else{
                    intent = new Intent(getActivity(), InvestManageActivity2.class);
                startActivity(intent);}
                break;
            case R.id.financeManagement:
                if (partyId.equals("")){
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent); }
                else{
                    intent = new Intent(getActivity(), FinanceManageActivity2.class);
                startActivity(intent);}
                break;
            case R.id.moneyFlowing:
                if (partyId.equals("")){
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);}
                else{
                    intent = new Intent(getActivity(), MoneyFlowingActivity2.class);
                startActivity(intent);}
                break;
            case R.id.securitySetting:
                if (partyId.equals("")){
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);}
                else{
                    intent = new Intent(getActivity(), SecuritySetting.class);
                startActivity(intent);}
                break;
            case R.id.recharge:
                if (partyId.equals("")){
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);}
                else{
//                    intent = new Intent(getActivity(), RechargeActivity.class);
//                startActivity(intent);
                    trueDialogShow("版本暂不支持");
 }

                break;
            case R.id.withdraw:
                if (partyId.equals("")){
                    intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("state", "0");
                    startActivity(intent);}
                else {
//                    intent = new Intent(getActivity(), WithdrawActivity.class);
//                startActivity(intent);
                trueDialogShow("版本暂不支持");
                }
                break;

        }
    }
    private void trueDialogShow(String hint) {
        View dialog = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.view_dialog_true, null);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_true_hint);
        ImageView imageView= (ImageView) dialog.findViewById(R.id.iv_dialog_image);
        imageView.setVisibility(View.GONE);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();

    }

}
